﻿using System;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Text.RegularExpressions;

namespace KKCai.Html
{
    public class CreateHtmlHandler : IHttpHandler, System.Web.SessionState.IRequiresSessionState
    {
        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            string requestedPath = context.Request.Url.PathAndQuery;
            string physicalPath = context.Request.PhysicalPath;
            string appPath = context.Request.ApplicationPath;
            string path = context.Request.Path;
            string query = context.Request.QueryString.ToString();

            #region 静态HTML页生成

            foreach (Rule rule in RuleManager.GetRules())
            {
                Regex re = new Regex(String.Format("^{0}$", RuleManager.ResolveUrl(appPath, rule.LookFor)), RegexOptions.IgnoreCase);

                if (re.IsMatch(requestedPath))
                {
                    string sendTo = RuleManager.ResolveUrl(appPath, re.Replace(requestedPath, rule.SendTo));
                    string htmlPath = context.Server.MapPath(sendTo);

                    if (!File.Exists(htmlPath))
                    {
                        context.Response.Filter = new Filter(context.Response.Filter, htmlPath);
                    }
                    else
                    {
                        if (File.GetLastWriteTime(htmlPath).AddMinutes(rule.TimeSpan) < DateTime.Now)
                        {
                            File.Delete(htmlPath);
                            context.Response.Filter = new Filter(context.Response.Filter, htmlPath);
                        }
                        else
                        {
                            context.Server.Transfer(sendTo);
                        }
                    }

                    break;
                }
            }
            
            #endregion

            context.RewritePath(path, null, query);
            PageParser.GetCompiledPageInstance(path, physicalPath, context).ProcessRequest(context);
        }

    }
}
